package mfuny.ggongal.admin.ship;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import mfuny.ggongal.admin.Server;
import mfuny.ggongal.admin.debug.Debug;
import mfuny.ggongal.admin.play.PlayService;
import mfuny.ggongal.admin.timetable.TimeDao;

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.springframework.web.servlet.ModelAndView;

import com.ibatis.sqlmap.client.SqlMapClient;

public class ShipService {
	SqlMapClient sqlMapper;
	ModelAndView mav;
	
	public ShipService() throws Exception {
		sqlMapper = Server.getSqlMapper();
		mav = new ModelAndView();
	}
	
	//송장번호 입력 페이지.
	public ModelAndView inputInvoiceNum() throws Exception {
		mav.clear();
		mav.setViewName("/shipping/inputInvoiceNum.ga");
		return mav;
	}
	
	//송장번호 입력 디테일 - 날짜선택 (left).
	@SuppressWarnings("unchecked")
	public ModelAndView inputInvoiceNum_leftForDays(String days) throws Exception {
		mav.clear();
		mav.setViewName("/shipping/inputInvoiceNum_leftForDays");
		
		TimeDao time = (TimeDao) sqlMapper.queryForObject("time_selectOne", days);
		List<Integer> todayTimes = new ArrayList<Integer>();
		List<Integer> specialTimes = new ArrayList<Integer>();
		
		if(time == null) {
			mav.addObject("specialTimes", specialTimes);
			return mav;
		}
		
		Method[] m = time.getClass().getMethods();
		
		//값있는 시간대 구하기.
		for(int i = 0; i < m.length; i++) {
			if(m[i].getName().substring(0, 4).equals("getH")) {
				if(m[i].invoke(time) != null) {
					todayTimes.add(Integer.parseInt((String)m[i].invoke(time)));
				}
			}
		}
		//스페셜 광고번호 구하기.
		List<Integer> specialAdNo = sqlMapper.queryForList("ad_specialNoForDay", todayTimes);
		
		for(int i = 0; i < m.length; i++) {
			boolean hasIt = false;
			for(int j = 0; j < specialAdNo.size(); j++) {
				if(m[i].getName().substring(0, 4).equals("getH")) {
					if(m[i].invoke(time) != null && Integer.parseInt((String)m[i].invoke(time)) == specialAdNo.get(j)) {
						hasIt = true;
					}
				}
			}
			if(hasIt) {
				specialTimes.add(Integer.parseInt(m[i].getName().substring(4)));
			}
		}
		
		mav.addObject("specialTimes", specialTimes);
		return mav;
	}
	
	//송장번호 입력 디테일 - 시간선택 (right).
	@SuppressWarnings({ "deprecation" })
	public ModelAndView inputInvoiceNum_rightForDays(String days, int time) throws Exception {
		mav.clear();
		mav.setViewName("/shipping/inputInvoiceNum_rightForDays");
		
		Date date = new Date();
		date.setYear(Integer.parseInt(days.split("-")[0]) - 1900);
		date.setMonth(Integer.parseInt(days.split("-")[1]) - 1);
		date.setDate(Integer.parseInt(days.split("-")[2]));
		date.setHours(time);
		date.setMinutes(0);
		date.setSeconds(0);
		
		TimeDao timeClass = (TimeDao) sqlMapper.queryForObject("time_selectOne", days);
		if(timeClass == null) {
			mav.addObject("winnerList", new ArrayList<Object>());
			return mav;
		}
		Method m = timeClass.getClass().getMethod("getH" + (time > 9 ? time : "0" + time));
		
		Object obj = m.invoke(timeClass);
		int ad_no = obj != null ? Integer.parseInt((String)obj) : 0;
		List<Object> winnerList = ad_no > 0 ? new PlayService().getWinnerForAd(ad_no, date) : new ArrayList<Object>();
		
		mav.addObject("winnerList", winnerList);
		return mav;
	}
	
	//송장번호 입력 처리.
	public ModelAndView setInvoice(String paramJSON) throws Exception {
		JSONObject json = (JSONObject) JSONValue.parse(paramJSON);
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		String msg = "";
		
		try{
			sqlMapper.startTransaction();
			sqlMapper.startBatch();
			int i = 0;
			for(i = 0; json.containsKey("invoices_" + i); i++) {
				paramMap.clear();
				paramMap.put("mygift_no", ((JSONObject)json.get("invoices_" + i)).get("mygift_no"));
				paramMap.put("invoicenum", ((JSONObject)json.get("invoices_" + i)).get("invoicenum"));
				sqlMapper.update("myGift_updateInvoicenum", paramMap);
			}
			
			int result = sqlMapper.executeBatch();
			
			//기존 버전.
//			if(result == i) {
//				msg = "정상적으로 처리되었습니다.";
//			}else{
//				throw new Exception();
//			}
			
			//문제가 발생하여 처리되지 않는것이 있는 경우 빼고 처리.
			if(result > 0) {
				msg = result + "건이 정상적으로 처리되었습니다.";
			} else {
				throw new Exception();
			}
			
			sqlMapper.commitTransaction();
		}catch(Exception e){
			Debug.toDebugFile(e, "setInvoice");
			msg = "오류가 발생하였습니다. 다시 시도해주십시오.";
			mav.addObject("value", msg);
		}finally{
			sqlMapper.endTransaction();
		}
		
		mav.clear();
		mav.setViewName("/blank");
		mav.addObject("value", msg);
		return mav;
	}
}
